import { fetchLogin } from '../services/login.service'
import { write } from '../utils/localstorge'
import { takeLatest } from '../utils/sageHelper'

export default {
  namespace: 'login',
  state: {
    userId: '',
    userName: '',
    phoneNumber: '',
    errorMsg: ''
  },
  reducers: {
    saveUserId(state, action) {
      return {
        ...state,
        ...action.payload
      }
    },
    saveUserName(state, action) {
      return {
        ...state,
        ...action.payload
      }
    },
    savePhoneNumber(state, action) {
      return {
        ...state,
        ...action.payload
      }
    }
  },
  effects: {
    login: takeLatest(function* login({ payload, onSuccess, onError }, { call }) {
      const { userName, phoneNumber } = payload
      console.log(payload)
      try {
        const response = yield call(fetchLogin, userName, phoneNumber)
        if (response) {
          yield onSuccess('Login success : )')
          yield write('userId', response.userId)
        } else {
          yield onError(response.message)
        }
      } catch (error) {
        yield onError(error.code, error.message)
      }
    })
  }
}
